import Vue from 'vue'

export default {
    state: {
        userInfo: null
    },
    getters: {
        userInfo(state){
            return state.userInfo;
        }
    },
    mutations: {
        setUserInfo(state, userInfo) {
            state.userInfo = userInfo;
        }
    },
    actions:{
        clearUserInfo({commit}){
            commit('setUserInfo', null);
            let keys=document.cookie.match(/[^ =;]+(?=\\=)/g);
            if (keys) {
                for (let i =  keys.length; i--;)
                    document.cookie=keys[i]+'=0;expires=' + new Date( 0).toUTCString()
            }
        },
        fetchUserInfo({commit, dispatch}) {
            return Vue.axios.get('/userInfo').then(res => {
                commit('setUserInfo', res.data);
                return Promise.resolve(res.data);
            }).catch(e => {
                dispatch('clearUserInfo');
                throw e;
            });
        }
    }
}